package controllers

import com.jfinal.aop.Before
import com.jfinal.aop.Clear
import com.jfinal.core.Controller
import com.jfinal.upload.UploadFile
import base.Message
import base.State
import controllers.interceptors.UserTokenCheckValidator
import services.GoodsService
import utils.LogUtil

@Before(UserTokenCheckValidator::class)
class GoodsController: Controller(){

    companion object{
        val TAG = GoodsController::class.simpleName!!
        const val TITLE = "title"
        const val DESC = "desc"
        const val PRICE = "price"
        const val CLASSES = "classes"
        const val LONGITUDE = "longitude"
        const val LATITUDE = "latitude"
        const val PAGE = "page"
        val PICTURES = List(8){index -> "pic$index"}
//        val PIC_MD5 = List(8){index -> "pic${index}_md5"}
    }

    private val service: GoodsService by lazy {
        GoodsService(this)
    }

    fun publish(){
        val pictures: MutableList<UploadFile> = mutableListOf()
        for (i in 0 until 8){
            val file = getFile(PICTURES[i])
            if (file != null){
                pictures.add(file)
            }
        }
//        LogUtil.i(TAG, "Pictures: length: ${pictures.size}")
        pictures.forEach {
            LogUtil.i(TAG, "name: ${it.fileName}")
        }
        if (pictures.isEmpty()){
            val message = Message(State.STATE_GOODS_PUBLISH_FAIL, data = State.getEorrorStr(State.ERROR_GOODS_AT_LEAST_ONE_PIC))
            renderJson(message)
            return
        }
        val title = get(TITLE)
        val desc = get(DESC)
        val longitude = get(LONGITUDE).toDouble()
        val latitude = get(LATITUDE).toDouble()
        val price = get(PRICE).toDouble()
        val classification = get(CLASSES)

        service.publish(pictures, title, desc, price, classification, longitude, latitude, UserTokenCheckValidator.getUserId(this))
    }

    fun collect(){
        val userId = UserTokenCheckValidator.getUserId(this)
        val recordId = getInt(RecordController.PARA_RECORD_ID)
        service.collectRecord(userId, recordId)
    }

    @Clear
    fun classifications(){
        service.getClassesList()
    }

    @Clear
    fun near(){
        val longitude = get(LONGITUDE)
        val latitude = get(LATITUDE)
        val page = getInt(PAGE)
        service.pullNearPublish(longitude, latitude, page)
    }

}